<template>
  <div id="AsnDetailList">
    <v-tableTitle :btnConfig="btnConfig" :tableSelectData="selectData" @backList="backList" @del="del"
      @newCreate="newCreate" @revocation="revocation" @orderPick="orderPick" @deliver="deliver"
      @saveDeatails="saveDeatails" @back="back"></v-tableTitle>
    <div class="detail">
      <v-navMenu :detailNav="detailNav" :menuData="menuData" @setMentActive="setMentActive" v-if="detailNav != 1">
      </v-navMenu>
      <component :data="{ detailData, argument, newFlag }" :is="currentComponent"></component>
    </div>
  </div>

</template>

<script>
import tableTitle from "commons/TableTitle";
import navMenu from "commons/NavMenu";
import baseMixin from "@/mixins/BaseMixin";
import config from "../Config";

export default {
  name: "DetailList",
  mixins: [baseMixin, config],
  data() {
    return {
      newFlag: false,
      mainFlag: false,
      detailFlag: false,
      argument: {},
      detailData: {},
      selectData: [],
      menuData: [
        {label: this.$t('out.sodetail', {no: 1}), index: "2"},
        {label: this.$t('out.sodetail', {no: 2}), index: "3"},
        {label: this.$t('config.batchProp'), index: "4"},
        {label: this.$t('out.pickdesc'), index: "5"},
        {label: this.$t('in.serialNumberInfo'), index: "6"}
      ],
      detailNav: "1",
      componentConfig: [
        {
          name: "Table",
          label: "table",
          component: () => import('./page/Table.vue')
        },
        {
          name: "OrderdetailSO1",
          label: this.$t('out.sodetail', {no: 1}),
          component: () => import('./page/OrderdetailSO1.vue')
        },
        {
          name: "OrderdetailSO2",
          label: this.$t('out.sodetail', {no: 2}),
          component: () => import('./page/OrderdetailSO2.vue')
        },
        {
          name: "OrderdetailLottable",
          label: this.$t('config.batchProp'),
          component: () => import('./page/OrderdetailLottable.vue')
        },
        {
          name: "OrderdetailPick",
          label: this.$t('out.pickdesc'),
          component: () => import('./page/OrderdetailPick.vue')
        },
        {
          name: "SerialNumberInformationList",
          label: this.$t('in.serialNumberInfo'),
          component: () => import("./page/OutSerialNumberInformationList.vue")
        }
      ]
    }
  },
  computed: {
    btnConfig() {
      if (this.detailNav == 1) {
        return [
          {
            label: this.$t('common.create'),
            certigier: !this.btnPermNameList.includes('WM020125'),
            invalid: "newCreate"
          },
          {
            label: this.$t('common.delete'),
            certigier: !this.btnPermNameList.includes('WM020126'),
            disabled: true,
            invalid: "del"
          },
          {
            type: "more",
            label: this.$t('out.action'),
            certigier: !this.btnPermNameList.includes('WM020127'),
            invalid: "down",
            btnConfig: [
              {
                label: this.$t('out.revocation'),
                certigier: !this.btnPermNameList.includes('WM020128'),
                disabled: true,
                invalid: "revocation"
              },
              {
                label: this.$t('out.pick'),
                certigier: !this.btnPermNameList.includes('WM020129'),
                disabled: true,
                invalid: "orderPick"
              },
              {
                label: this.$t('config.deliver'),
                certigier: !this.btnPermNameList.includes('WM020130'),
                disabled: true,
                invalid: "deliver"
              },
            ]
          },
        ]
      } else if (this.newFlag) {
        return [
          {
            label: this.$t('app.saveDetail'),
            certigier: !this.btnPermNameList.includes('WM020131'),
            invalid: "saveDeatails",
          },
          {label: this.$t('common.return'), certigier: !this.btnPermNameList.includes('WM020132'), invalid: "back"},
        ]
      } else {
        return [
          {label: this.$t('common.return'), certigier: !this.btnPermNameList.includes('WM020132'), invalid: "backList"},
        ]
      }
    },
    currentComponent() {
      return this.componentConfig[this.detailNav - 1].component;
    }
  },
  methods: {
    deliver(data) {
      data.forEach(async (item, index) => {
        try {
          let res = await this.$api.post(`/getDeliverPickdetailkeyBySku`, item);
          
            this.$message.success(res.returnMgr);
            let page = sessionStorage.getItem('page');
            this.$children[1].getTableData(page, {});
        } catch (e) {
          this.$message.error(e);
        } finally {
          this.$children[1].$refs.table.delSelectData(item, index);
        }
      });
    },
    orderPick(data) {
      data.forEach(async (item, index) => {
        try {
          let res = await this.$api.post(`/getPickdetailListByPicking`, item);
          
            this.$message.success(res.returnMgr);
            let page = sessionStorage.getItem('page');
            this.$children[1].getTableData(page, {});
        } catch (e) {
          this.$message.error(e);
        } finally {
          this.$children[1].$refs.table.delSelectData(item, index);
        }
      });
    },
    revocation(data) {
      this.argument = {orderkey:this.$parent.$refs.detail.detailData.orderkey};
      data.forEach(async (item, index) => {
        try {
          let res = await this.$api.get(`/ordersRevokeSingle/${this.argument.orderkey}/${item.orderlinenumber}`);
          
            this.$message.success(res.returnMgr);
            let page = sessionStorage.getItem('page');
            this.$children[1].getTableData(page, {});
        } catch (e) {
          this.$message.error(e);
        } finally {
          this.$children[1].$refs.table.delSelectData(item, index);
        }
      });
    },
    //删除数据
    async del(data) {
      try {
        let res = await this.$api.post(`/deleteOrdersDetail`, data);
        
          this.$message.success(res.returnMgr);
          let page = sessionStorage.getItem('page')
          this.$children[1].getTableData(1, {})
        
      } catch (e) {
        this.$message.error(e);
      } finally {
        this.$children[1].$refs.table.delSelectData(data);
      }
    },
    //选中的数据
    setSelectData(data) {
      this.selectData = data;
    },
    //进入详情
    async setdialog(data) {
      this.argument = {orderkey:this.$parent.$refs.detail.detailData.orderkey};
      try {
        let res = await this.$api.post(`/queryOrderdetailByOrderlinenumber`, {
          orderkey: this.argument.orderkey,
          orderlinenumber: data.orderlinenumber
        });
        
          this.detailData = res.bean;
          this.detailNav = "2";
        
      } catch (e) {
        this.$message.error(e);
      }
    },
    //返回试图
    backList() {
      this.detailNav = "1";
      this.$store.commit("setDetailsNew", false);
    },
    //新建
    async newCreate() {
      this.detailData = {
        adjustedqty: 0,
        allocatestrategytype: "1",
        altsku: " ",
        cartonbreak: " ",
        cartongroup: " ",
        convertedqty: 0,
        cubicmeter: 0,
        extendedprice: 0,
        externlineno: "",
        externorderkey: " ",
        facility: " ",
        forte_flag: "I",
        fulfillqty: 0,
        generatecontainerdetail: "0",
        hundredweight: 0,
        id: " ",
        issubstitute: 0,
        lot: " ",
        lottable01: " ",
        lottable02: " ",
        lottable03: " ",
        lottable06: " ",
        lottable07: " ",
        lottable08: " ",
        lottable09: " ",
        lottable10: " ",
        manufacturersku: " ",
        minshippercent: 0,
        oktosubstitute: 0,
        openqty: 0,
        opprequest: "0",
        oqcautoadjust: "0",
        oqcrequired: "0",
        orderlinenumber: "",
        origcaseqty: 0,
        originalqty: 0,
        origlayerqty: 0,
        origpalletqty: 0,
        packkey: "STD",
        pallet_id: " ",
        pickcode: " ",
        product_cube: 0,
        product_weight: 0,
        qtyallocated: 0,
        qtyintransit: 0,
        qtypicked: 0,
        qtypreallocated: 0,
        qtytoprocess: 1,
        retailsku: " ",
        sequence: 0,
        shelflife: 0,
        shipgroup01: "N",
        shipgroup02: "N",
        shipgroup03: "N",
        shippedqty: 0,
        sku: "",
        skurotation: "Lot",
        status: "04",
        storerkey: "",
        sub_flag: " ",
        tariffkey: "XXXXXXXXXX",
        tax01: 0,
        tax02: 0,
        unitprice: 0,
        uom: "EA",
        updatesource: "0",
        workorderkey: " ",
        wpreleased: "0",
      };
      this.argument = {orderkey:this.$parent.$refs.detail.detailData.orderkey};
      try {
        let res = await this.$api.get(`/queryOrderdetailMaxLine/${this.argument.orderkey}`);
        
          this.$store.commit("setDetailsNew", true);
          this.detailData.orderlinenumber = res.bean;
          this.detailData.externlineno = "WMS" + res.bean;
          this.detailData.orderkey = this.selectData.orderkey;
          this.detailNav = "2";
        
      } catch (e) {
        this.$message.error(e);
      }
    },
    //导航值
    setMentActive(key) {
      this.detailNav = key;
    },
    //保存明细
    async saveDeatails() {
      this.$parent.$refs["detail"].$children[1].$children[0].$refs["from"].validate((valid) => {
        if (valid) {
          this.mainFlag = true;
          this.$children[2].$children[0].$refs["from"].validate((valid) => {
            if (valid) {
              this.detailFlag = true;
              if (this.detailFlag && this.mainFlag) {
                //上下数据均已校准 可以开始保存
                let detail = this.$parent.$children[1].detailData;
                let detailList = this.detailData;
                if (detailList.openqty === 0) {
                  this.$message.error(this.$t('msg.msg63'));
                  return;
                }
                let reg = /^(\-|\+)?\d+(\.\d+)?$/;//正数、负数、和小数
                if (detail.stop != null && detail.stop != '' && !reg.test(detail.stop)) {
                  this.$message.error(this.$t('msg.msg64'))
                  return
                }
                let data = {
                  ...detail,
                  orderdetail: [{...detailList}]
                }
                try {
                  this.$api.post("/excuteOrders", data).then(res => {
                    
                      this.$message.success(res.returnMgr);
                      this.$api.get(`/queryOrderdetailMaxLine/${detail.orderkey}`).then(res1 => {
                          let str = res1.data.bean;
                          // 回归第一页 且清空其他页面的所有数据
                          this.detailData = {
                            adjustedqty: 0,
                            allocatestrategytype: "1",
                            altsku: " ",
                            cartonbreak: " ",
                            cartongroup: " ",
                            convertedqty: 0,
                            cubicmeter: 0,
                            extendedprice: 0,
                            externlineno: "WMS" + str,
                            externorderkey: " ",
                            facility: " ",
                            forte_flag: "I",
                            fulfillqty: 0,
                            generatecontainerdetail: "0",
                            hundredweight: 0,
                            id: " ",
                            issubstitute: 0,
                            lot: " ",
                            lottable01: " ",
                            lottable02: " ",
                            lottable03: " ",
                            lottable06: " ",
                            lottable07: " ",
                            lottable08: " ",
                            lottable09: " ",
                            lottable10: " ",
                            manufacturersku: " ",
                            minshippercent: 0,
                            oktosubstitute: 0,
                            openqty: 0,
                            opprequest: "0",
                            oqcautoadjust: "0",
                            oqcrequired: "0",
                            orderlinenumber: str,
                            origcaseqty: 0,
                            originalqty: 0,
                            origlayerqty: 0,
                            origpalletqty: 0,
                            packkey: "STD",
                            pallet_id: " ",
                            pickcode: " ",
                            product_cube: 0,
                            product_weight: 0,
                            qtyallocated: 0,
                            qtyintransit: 0,
                            qtypicked: 0,
                            qtypreallocated: 0,
                            qtytoprocess: 1,
                            retailsku: " ",
                            sequence: 0,
                            shelflife: 0,
                            shipgroup01: "N",
                            shipgroup02: "N",
                            shipgroup03: "N",
                            shippedqty: 0,
                            sku: "",
                            skurotation: "Lot",
                            status: "04",
                            storerkey: data.storerkey,
                            sub_flag: " ",
                            tariffkey: "XXXXXXXXXX",
                            tax01: 0,
                            tax02: 0,
                            unitprice: 0,
                            uom: "EA",
                            updatesource: "0",
                            workorderkey: " ",
                            wpreleased: "0",
                            orderkey: this.$store.state.routeId
                          };
                          this.detailNav = "2";
                        
                      })
                  });
                } catch (e) {
                  this.$message.error(e);
                }
              }
            }
          })
        }
      })
    },
    // 返回到列表页面
    back() {
      this.$router.push({name: "asn"});
    },
  },
  mounted() {
    const query = this.$route.query;
    if(query.newFlag){
      this.newFlag = true;
      this.detailNav = "2";
      this.detailData = {
        adjustedqty: 0,
        allocatestrategytype: "1",
        altsku: " ",
        cartonbreak: " ",
        cartongroup: " ",
        convertedqty: 0,
        cubicmeter: 0,
        extendedprice: 0,
        externlineno: "WMS00001",
        externorderkey: " ",
        facility: " ",
        forte_flag: "I",
        fulfillqty: 0,
        generatecontainerdetail: "0",
        hundredweight: 0,
        id: " ",
        issubstitute: 0,
        lot: " ",
        lottable01: " ",
        lottable02: " ",
        lottable03: " ",
        lottable06: " ",
        lottable07: " ",
        lottable08: " ",
        lottable09: " ",
        lottable10: " ",
        manufacturersku: " ",
        minshippercent: 0,
        oktosubstitute: 0,
        openqty: 0,
        opprequest: "0",
        oqcautoadjust: "0",
        oqcrequired: "0",
        orderlinenumber: "00001",
        origcaseqty: 0,
        originalqty: 0,
        origlayerqty: 0,
        origpalletqty: 0,
        packkey: "STD",
        pallet_id: " ",
        pickcode: " ",
        product_cube: 0,
        product_weight: 0,
        qtyallocated: 0,
        qtyintransit: 0,
        qtypicked: 0,
        qtypreallocated: 0,
        qtytoprocess: 1,
        retailsku: " ",
        sequence: 0,
        shelflife: 0,
        shipgroup01: "N",
        shipgroup02: "N",
        shipgroup03: "N",
        shippedqty: 0,
        sku: "",
        skurotation: "Lot",
        status: "04",
        storerkey: "",
        sub_flag: " ",
        tariffkey: "XXXXXXXXXX",
        tax01: 0,
        tax02: 0,
        unitprice: 0,
        uom: "EA",
        updatesource: "0",
        workorderkey: " ",
        wpreleased: "0",
        orderkey: ""
      };
    }else{
      this.newFlag = false;
      this.argument = query;
    }
  },
  components: {
    "v-tableTitle": tableTitle,
    "v-navMenu": navMenu,
  },
  watch: {
    detailNav: {
      handler(data) {
        console.log('order detailNav = %o', data);
        if (data != "1") {
          this.$store.commit("setTemporary", true);
        } else {
          this.$store.commit("setTemporary", false);
        }
      },
      immediate: true,
      deep: true
    },
    selectData(data) {
      if (this.permissionStatus) {
        if (data.length > 0) {
          this.deleteDetailStatus = this.pickingStatus = this.deliverDetailStatus = false;
          this.deliver2Status = false;
          this.selectDetailValue = event;
        } else {
          this.deliver2Status = true;
          this.deleteDetailStatus = this.pickingStatus = this.deliverDetailStatus = true;
        }
      }
    }
  }
}
</script>

<style>
</style>
